package com.xinchao.job.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.xinchao.common.util.ListUtil;
import com.xinchao.common.vo.DeviceOffLineVO;
import com.xinchao.job.mapper.dmp.DeviceInfoMapper;
import com.xinchao.job.service.asynccomment.AsyncCommentService;

@Service("deviceOffLineJobService")
public class DeviceOffLineJobService  {
	@Autowired
	private DeviceInfoMapper deviceInfoMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private AsyncCommentService asyncCommentService;
	@Value("${xc.device.report.time.redundancy}")
    private Integer redundancyTime;
	
	/**
	 * 终端设备离线jobservice 执行逻辑分为两步：
	 * 	 step1 查询出所有超时未访问的设备，针对未在关机时间范围内离线的“异常离线设备”，添加提醒记录，发送短信和邮件
	 *	 step2 更新数据库终端的状态
	 */
	public void deviceOffLine() {
		
		// 给出一个超时比对时间，这里的时间存放在配置文件中
		long timeDiff = System.currentTimeMillis() - (redundancyTime)*1000;
		
		// step1 查询出所有超时未访问的设备，针对未在关机时间范围内离线的“异常离线设备”，添加提醒记录，发送短信和邮件
		// step2 更新数据库终端的状态
		deviceOffLineHandler(timeDiff);
		
	}

	private void deviceOffLineHandler(long timeDiff) {
		// job单次处理数据量40000条
		List<DeviceOffLineVO> offLineDeviceList = deviceInfoMapper.getOffLineDevice(timeDiff,40000);
		if ( CollectionUtils.isNotEmpty(offLineDeviceList) ) {
			// 每2000条数据多线程异步处理 
			List<List<DeviceOffLineVO>> singleLimitAssign = ListUtil.singleLimitAssign(offLineDeviceList, 2000);
			Map<Object, Object> adminUserMap = userService.getAdminUserMap();
			for ( List<DeviceOffLineVO> list : singleLimitAssign) {
				asyncCommentService.handleOfflineDevice(list,adminUserMap);
			}
		}
	}
	
}
